/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
package com.jeesite.modules.kj.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.excel.ExcelExport;
import com.jeesite.modules.aliyun.msg.AliyunSmsUtils;
import com.jeesite.modules.kj.entity.*;
import com.jeesite.modules.kj.enums.IntegralEnum;
import com.jeesite.modules.kj.service.KjActivityJobService;
import com.jeesite.modules.kj.utils.IntegralUtil;
import com.jeesite.modules.kj.utils.SystemLogUtil;
import com.jeesite.modules.sys.entity.Log;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.poi.hpsf.Decimal;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jeesite.common.config.Global;
import com.jeesite.common.entity.Page;
import com.alibaba.fastjson.JSONValidator;
import com.jeesite.common.codec.EncodeUtils;
import com.jeesite.common.web.BaseController;
import com.jeesite.modules.kj.service.KjMemberJobService;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * kj_member_jobController
 * @author hzy
 * @version 2021-07-12
 */
@Controller
@RequestMapping(value = "${adminPath}/kj/kjMemberJob")
public class KjMemberJobController extends BaseController {

	@Autowired
	private KjActivityJobService kjActivityJobService;
	@Autowired
	private KjMemberJobService kjMemberJobService;

	@Value("${msg.sms.template.lovePointsArrive}")
	private String lovePointsArrive;


	@Value("${msg.sms.template.noLovePointsArrive}")
	private String noLovePointsArrive;

	/**
	 * 获取数据
	 */
	@ModelAttribute
	public KjMemberJob get(String id, boolean isNewRecord) {
		return kjMemberJobService.get(id, isNewRecord);
	}
	/**
	 * 查询列表
	 */
	@RequiresPermissions("kj:kjMemberJob:view")
	@RequestMapping(value = {"list", ""})
	public String list(KjMemberJob kjMemberJob, Model model) {
		model.addAttribute("kjMemberJob", kjMemberJob);
		return "modules/kj/kjMemberJobList";
	}

	/**
	 * 查询列表数据
	 */
	@RequiresPermissions("kj:kjMemberJob:view")
	@RequestMapping(value = "listData")
	@ResponseBody
	public Page<KjMemberJob> listData(KjMemberJob kjMemberJob, HttpServletRequest request, HttpServletResponse response) {
		kjMemberJob.getKjActivity().setStatus(KjMemberJob.STATUS_NORMAL);
		kjMemberJob.setPage(new Page<>(request, response));
		Page<KjMemberJob> page = kjMemberJobService.findPage(kjMemberJob);
		return page;
	}

	/**
	 * 查看编辑表单
	 */
	@RequiresPermissions("kj:kjMemberJob:view")
	@RequestMapping(value = "form")
	public String form(KjMemberJob kjMemberJob, Model model) {
		model.addAttribute("kjMemberJob", kjMemberJob);
		return "modules/kj/kjMemberJobForm";
	}



	/**
	 * 活动积分发放
	 */
	@RequiresPermissions("kj:kjActivityIntegral:send")
	@RequestMapping(value = "integralManage")
	public String integralManage(KjMemberJob kjMemberJob, Model model) {
		model.addAttribute("kjMemberJob", kjMemberJob);
		return "modules/kj/kjIntegralManageList";
	}


	/**
	 * 活动积分发放数据列表
	 */
	@RequiresPermissions("kj:kjActivityIntegral:send")
	@RequestMapping(value = "integralManageList")
	@ResponseBody
	public Page<KjMemberJob> integralManageList(KjMemberJob kjMemberJob, KjMember kjMember, Date startTime, Date endTime, HttpServletRequest request, HttpServletResponse response) {
		kjMemberJob.setPage(new Page<>(request, response));
		kjMemberJob.setApproveStatus(KjMemberJob.OK);
		kjMemberJob.setKjMember(kjMember);
		//如果开始时间大于结束时间，则颠倒两条数据
		if(endTime!=null && startTime!=null && endTime.compareTo(startTime) < 0){
			kjMemberJob.getKjActivity().setCreateDate_lte(startTime);
			kjMemberJob.getKjActivity().setCreateDate_gte(endTime);
		}else {
			kjMemberJob.getKjActivity().setCreateDate_lte(endTime);
			kjMemberJob.getKjActivity().setCreateDate_gte(startTime);
		}
		kjMemberJob.getKjActivity().setStatus(KjMemberJob.STATUS_NORMAL);
		Page<KjMemberJob> page = kjMemberJobService.findPage(kjMemberJob);
		return page;
	}


	/**
	 * 活动积分发放编辑表单
	 */
	@RequiresPermissions("kj:kjActivityIntegral:send")
	@RequestMapping(value = "kjIntegralManageForm")
	public String integralManageForm(KjMemberJob kjMemberJob, Model model) {
		KjActivityJob job = kjActivityJobService.get(kjMemberJob.getJobId());
		if(kjMemberJob.getIntegrals() == null || kjMemberJob.getIntegrals().compareTo(BigDecimal.ZERO) <= 0) {
			kjMemberJob.setIntegrals(job.getIntegrals());
			kjMemberJob.setServiceTime(job.getServiceTime());
		}
		if(kjMemberJob.getServiceTime() == null) {
			kjMemberJob.setServiceTime(job.getServiceTime());
		}
		model.addAttribute("kjMemberJob", kjMemberJob);
		return "modules/kj/kjIntegralManageForm";
	}


	/**
	 * 保存数据
	 */
	//todo 发放积分
	@RequiresPermissions("kj:kjMemberJob:edit")
	@PostMapping(value = "sendIntegral")
	@ResponseBody
	public String sendIntegral(@Validated KjMemberJob kjMemberJob, String action, HttpServletRequest request) {
		if(!KjMemberJob.SENDED.equals(kjMemberJob.getSendStatus())){
			if(action.equals("submit")) {
				KjMember member = kjMemberJob.getKjMember();
				KjActivityJob job = kjActivityJobService.get(kjMemberJob.getJobId());
				//通知发放积分成功
				AliyunSmsUtils.sendMessages(kjMemberJob.getKjMember().getMobile(),lovePointsArrive,new HashMap<>());
				IntegralUtil.addIntegrals(member, kjMemberJob.getId(), job.getJobTypeId(), IntegralEnum.ACTIVITY, kjMemberJob.getIntegrals(), kjMemberJob.getServiceTime(), "参与活动" + kjMemberJob.getActivityName() + "-" + job.getJobName());
				SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "发放积分", Log.TYPE_UPDATE, "已发放", kjMemberJob.getKjMember().getName() + "报名的" + "\"" + job.getJobName() + "\"", request);
				kjMemberJob.setSendStatus(KjMemberJob.SENDED);
			}else{
				Map<String, Object> tplData=new HashMap<>();
				tplData.put("activityName",kjMemberJob.getActivityName());
				//通知发放积分被拒绝
				AliyunSmsUtils.sendMessages(kjMemberJob.getKjMember().getMobile(),noLovePointsArrive,tplData);
				SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "发放积分", Log.TYPE_UPDATE, "拒绝发放", kjMemberJob.getKjMember().getName() + "报名的" + "\"" + kjMemberJob.getJobName() + "\"", request);
				kjMemberJob.setSendStatus(KjMemberJob.SENDRELECT);
				kjMemberJob.setServiceTime(null);
				kjMemberJob.setIntegrals(null);
			}
		}
		kjMemberJobService.save(kjMemberJob);
		kjActivityJobService.updateAttentions(kjMemberJob.getJobId());
		return renderResult(Global.TRUE, text("已" + (action.equals("submit") ? "发放" :"拒绝发放") +  "积分！"));

	}






	/**
	 * 活动积分修改编辑表单
	 */
	@RequiresPermissions("kj:kjActivityIntegral:send")
	@RequestMapping(value = "kjIntegralManageEditForm")
	public String integralManageEditForm(KjMemberJob kjMemberJob, Model model) {
		kjMemberJob.setRemarks(null);
		model.addAttribute("kjMemberJob", kjMemberJob);
		return "modules/kj/kjIntegralManageEditForm";
	}



	/**
	 * 修改数据保存
	 */
	@RequiresPermissions("kj:kjMemberJob:edit")
	@PostMapping(value = "editIntegral")
	@ResponseBody
	public String editIntegral(@Validated KjMemberJob kjMemberJob, BigDecimal modifyPoints ,BigDecimal oldServiceTime, String action, HttpServletRequest request) {
		KjMember member = kjMemberJob.getKjMember();
		KjActivityJob job = kjActivityJobService.get(kjMemberJob.getJobId());
		IntegralUtil.addIntegrals(member, kjMemberJob.getId(), job.getJobTypeId(), IntegralEnum.ADMIN_OPERATE, modifyPoints, kjMemberJob.getServiceTime().subtract(oldServiceTime), kjMemberJob.getRemarks());

		SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "修改发放积分", Log.TYPE_UPDATE, "修改积分", kjMemberJob.getKjMember().getName() + "报名的" + "\"" + job.getJobName() + "\"", request);
		kjMemberJob.setIntegrals(kjMemberJob.getIntegrals().add(modifyPoints));
		kjMemberJob.setRemarks(null);
		kjMemberJobService.save(kjMemberJob);
		kjActivityJobService.updateAttentions(kjMemberJob.getJobId());
		return renderResult(Global.TRUE, text("修改发放积分成功"));

	}


	/**
	 * 保存数据
	 */
	@RequiresPermissions("kj:kjMemberJob:edit")
	@PostMapping(value = "save")
	@ResponseBody
	public String save(@Validated KjMemberJob kjMemberJob, HttpServletRequest request) {
		//验证报名名额是否充足
		KjMemberJob oldData = kjMemberJobService.get(kjMemberJob.getId());
		if(!oldData.getApproveStatus().equals(KjMemberJob.OK) && kjMemberJob.getApproveStatus().equals(KjMemberJob.OK)) {
			KjActivityJob job = kjActivityJobService.get(kjMemberJob.getJobId());
			if(job.getLimitNum() <= job.getApprovedNum()){
				return renderResult(Global.FALSE, "该岗位名额已满，无法通过该用户报名");
			}
			SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "报名审核", Log.TYPE_UPDATE, "审核通过", kjMemberJob.getKjMember().getName() + "报名的" + "\"" + job.getJobName() + "\"", request);
			kjMemberJobService.sendAttentionSms(kjMemberJob);
		}
		if(!oldData.getApproveStatus().equals(KjMemberJob.REJECT) && kjMemberJob.getApproveStatus().equals(KjMemberJob.REJECT)) {
			SystemLogUtil.insertAdminOperate(UserUtils.getUser(), "报名审核", Log.TYPE_UPDATE, "审核不通过", kjMemberJob.getKjMember().getName() + "报名的" + "\"" + kjMemberJob.getJobName() + "\"", request);
			kjMemberJobService.sendAttentionSms(kjMemberJob);
		}
//		kjMemberJob.setRemarks("");
		kjMemberJobService.save(kjMemberJob);
		kjActivityJobService.updateAttentions(kjMemberJob.getJobId());
		return renderResult(Global.TRUE, text("保存参与活动成功！"));
	}

	/**
	 * 删除数据
	 */
	@RequiresPermissions("kj:kjMemberJob:edit")
	@RequestMapping(value = "delete")
	@ResponseBody
	public String delete(KjMemberJob kjMemberJob) {
		kjMemberJobService.delete(kjMemberJob);
		return renderResult(Global.TRUE, text("删除参与活动成功！"));
	}

	/**
	 * 列表选择对话框
	 */
	@RequiresPermissions("kj:kjMemberJob:view")
	@RequestMapping(value = "kjMemberJobSelect")
	public String empUserSelect(KjMemberJob kjMemberJob, String selectData, Model model) {
		String selectDataJson = EncodeUtils.decodeUrl(selectData);
		if (selectDataJson != null && JSONValidator.from(selectDataJson).validate()){
			model.addAttribute("selectData", selectDataJson);
		}
		model.addAttribute("KjMemberJob", kjMemberJob);
		return "modules/kj/kjMemberJobSelect";
	}



	/**
	 * 导出报名数据
	 */
	@RequiresPermissions("kj:kjMemberJob:view")
	@RequestMapping(value = "exportData")
	public void exportData(KjMemberJob kjMemberJob, Boolean isAll, String ctrlPermi, HttpServletResponse response) {
		kjMemberJob.getKjActivity().setStatus(KjMemberJob.STATUS_NORMAL);
		kjMemberJob.setPageNo(null);
		kjMemberJob.setPageSize(null);

		List<KjMemberJob> list = kjMemberJobService.findList(kjMemberJob);
		String fileName = "报名数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("报名数据", KjMemberJob.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}


	/**
	 * 导出报名数据
	 */
	@RequiresPermissions("kj:kjMemberJob:view")
	@RequestMapping(value = "exportIntegralData")
	public void exportIntegralData(KjMemberJob kjMemberJob,KjMember kjMember,Date startTime, Date endTime, Boolean isAll, String ctrlPermi, HttpServletResponse response) {

		kjMemberJob.getKjActivity().setStatus(KjMemberJob.STATUS_NORMAL);
		kjMemberJob.setPageNo(null);
		kjMemberJob.setPageSize(null);
		kjMemberJob.setKjMember(kjMember);
		kjMemberJob.setApproveStatus(KjMemberJob.OK);
		//如果开始时间大于结束时间，则颠倒两条数据
		if(endTime!=null && startTime!=null && endTime.compareTo(startTime) < 0){
			kjMemberJob.getKjActivity().setCreateDate_lte(startTime);
			kjMemberJob.getKjActivity().setCreateDate_gte(endTime);
		}else {
			kjMemberJob.getKjActivity().setCreateDate_lte(endTime);
			kjMemberJob.getKjActivity().setCreateDate_gte(startTime);
		}
		List<KjMemberJob> list = kjMemberJobService.findList(kjMemberJob);
		String fileName = "积分数据" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
		try(ExcelExport ee = new ExcelExport("积分数据", KjMemberJobIntegralExport.class)){
			ee.setDataList(list).write(response, fileName);
		}
	}

}
